package com.mywebsite.Controller;


import com.mywebsite.Domain.Picture;
import com.mywebsite.Domain.User;
import com.mywebsite.Service.PictureService;
import com.mywebsite.Service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("v1/upload")
@CrossOrigin
public class PictureController {
    @Autowired
    UserService userService;
    @Autowired
    PictureService pictureService;

    @Value("${upload.userpicpath}")
    private String basePath;

    @PostMapping
    public Result getpic(@RequestPart MultipartFile file, @RequestParam("username") String username){
        //file是一个临时文件，需要转存到指定的位置，否则本次请求完成后临时文件会被删除
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID生成文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //不存在，创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            return new Result(Code.Error,"上传失败"+fileName);
        }
        pictureService.upload(username, basePath+fileName);
        return new Result(Code.Success,"上传成功"+fileName);
    }




}
